package com.github.baichuan.web.reactive;

import com.github.baichuan.web.security.JwtCodec;
import org.springframework.core.MethodParameter;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Optional;

public class JwtPrincipalArgumentResolver<T> implements HandlerMethodArgumentResolver {
    private JwtCodec<T> codec;

    public JwtPrincipalArgumentResolver(JwtCodec<T> codec){
        this.codec = codec;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Optional<Type> optional = Arrays.stream(this.codec.getClass().getGenericInterfaces())
                .filter(clazz -> clazz.getClass().isAssignableFrom(JwtCodec.class))
                .findFirst();
        if(optional.isPresent()){
            Type type = optional.get();
            Class<T> clazz = (Class<T>)((ParameterizedType)type).getActualTypeArguments()[0];
            return clazz.isAssignableFrom(parameter.getParameterType());
        } else {
            return false;
        }
    }

    @Override
    public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
        return null;
    }
}
